<template>
  <div>
    <g-map @map="getMap"></g-map>
    <marker-set-panel class="markerSetPanel" @selectIcon="showSelectIcon" @showList="showList"></marker-set-panel>
    <location-panel class="locationPanel" v-model="searchVal" :lnglat="zoomAndCenter.center" @zoomAndCenter="setZoomAndCenter"></location-panel>
    <anchors-bar v-model="achorsInfo" v-if="showAnchors" @clickEvent="clickEvent"></anchors-bar>
    <camera-list v-if='false' class="cameraList"></camera-list>
    <div :class="{'ancSelectBox': openAndCloseFlag, 'ancUnSelectBox': !openAndCloseFlag}">
      <span @click="openAndClose">
        <img src="../../assets/images/mapIconTest/selected.png" alt="">
      </span>
    </div>
    <marker-list v-if="openAndCloseFlag && ancSelectMarkers.length > 0" class="markerList" v-model="ancSelectMarkers"></marker-list>
  </div>
</template>
<script>
import gMap from '@/components/demo/amap'
import markerSetPanel from '@/components/panel/markerSetPanel'
import locationPanel from '@/components/panel/locationPanel'
import anchorsBar from '@/components/panel/anchorsBar'
import cameraList from '@/components/demo/cameraList'
import markerList from '@/components/demo/markerList'
export default {
  name: 'demo',
  data () {
    return {
      ancSelectMarkers: [], // 矩形选中 标注
      openAndCloseFlag: false, // 开启关闭矩形选中
      mouseTool: '',
      selectZoomMouseDownHandler: '',
      selectZoomDrawHandler: '',
      showAnchors: false,
      achorsInfo: {
        markerState: 'unEdit',
        name: '',
        remark: '',
        zoom: '',
        position: ['', '']
      },
      selectMarker: '',
      searchVal: '',
      // 标注面板信息列表
      markerSetData: {
        markers: [], // 标注面板图标信息
        maximum: 4 // 面板一行显示最大条数
      },
      clickCancel: true,
      listenerFlag: false,
      map: '',
      markers: [],
      pointerCheckedList: [],
      zoomAndCenter: {
        zoom: '',
        center: []
      }
    }
  },
  methods: {
    KeywordLocationMapCenterPoint (ctx, inputId) {
      AMapUI.loadUI(['misc/PoiPicker'], PoiPicker => {
        let poiPicker = new PoiPicker({
          input: inputId
        })
        //初始化poiPicker
        this.marker = new AMap.Marker()
        //选取了某个POI
        poiPicker.on('poiPicked', poiResult => {
          let poi = poiResult.item
          this.marker.setMap(ctx)
          if (inputId === 'pickerInput') {
            this.searchVal = poi.name
          } else {
            this.searchVal3D = poi.name
          }
          if (!poi.location) {
            return
          }
          this.marker.setMap(ctx)
          this.marker.setPosition(poi.location)
          let extData = {type: 'center'}
          this.marker.setExtData(extData) //给标记点添加type属性
          ctx.setZoomAndCenter(19, this.marker.getPosition())
        })
      })
    },
    getZoomAndCenter () {
      var zoom = this.map.getZoom()
      var center = [this.map.getCenter().lng, this.map.getCenter().lat]
      this.zoomAndCenter['zoom'] = zoom
      this.zoomAndCenter['center'] = center
    },
    setZoomAndCenter ({zoom, center} = {}) {
      let extData = {type: 'center'}
      center = [...center]
      console.log(zoom, center)
      this.map.setZoomAndCenter(zoom, center)
      this.marker.setPosition(center)
      this.marker.setMap(null)
      this.marker.setMap(this.map);
      this.marker.setExtData(extData) //给标记点添加type属性
    },
    cancelAllMarkers () {
      this.map.clearMap()
      window.localStorage.removeItem('markersMsg')
    },
    showSelectIcon (data) {
      this.pointerCheckedList = data
    },
    showList (data) {
      console.log(data)
    },
    getMap (map) {
      this.map = map
    },
    cancleMarker () {
      this.markers[this.markers.length - 1] && this.map.remove(this.markers[this.markers.length - 1].marker)
      this.markers.pop()
      this.saveMarkers(this.markers)
    },
    saveMarkers (markers) {
      var markersMsg = markers.map(v => v.msg)
      window.localStorage.setItem('markersMsg', JSON.stringify(markersMsg))
    },
    setMarker ({position, icon, markerState, markerType}) {
      if (!this.map) {
        return
      }
      var src = require(`../../assets/images/mapIcon/${icon}.png`)
      var markerHtml = (isSelect, src, markerState) => {
        switch (markerState) {
          case 'unLink':
            var markerStateHtml = `<span class="iconMarkerUnlink"></span>`
            break
          case 'normal':
            markerStateHtml = ''
            break
          case 'unEdit':
          default:
            markerStateHtml = `<span class="iconMarkerUnedit"></span>`
            break
        }
        return `<div class="${isSelect ? 'markerSelect' : 'markerUnSelect'}">${markerStateHtml}<img src="${src}" alt=""></div>`
      }
      var marker = new AMap.Marker({
        content: markerHtml(false, src, markerState),
        offset: new AMap.Pixel(-25, -25),
        position: position,
        topWhenClick: true
      })
      marker.setExtData({markerType})
      /**
       * 标记点点击监听函数
       * @author chend(cdhahaha@163.com)
       * @createDate 2018-07-25
       */
      marker.on('click', (e) => {
        var extData = {}
        var extDataTemp = e.target.getExtData()
        var isSelect = extDataTemp['isSelect'] // 当前点击标记的选中状态
        var markerStateTemp = extDataTemp.markerState || markerState
        /**
         * if内语句：清除上一个标记的表现
         * @author chend(cdhahaha@163.com)
         * @createDate 2018-07-25
         */
        if (this.selectMarker) {
          var selectMarkerExtData = this.selectMarker.getExtData()
          this.selectMarker.setContent(markerHtml(false, selectMarkerExtData.src, selectMarkerExtData.markerState))
          this.selectMarker.setOffset(new AMap.Pixel(-25, -25))
          selectMarkerExtData['isSelect'] = false
          this.selectMarker.setExtData(selectMarkerExtData)
        }
        if (isSelect) {
          /**
           * 代码段设置未选中状态下的标记样式。如果上次为选中状态isSelect: true，则设置当前样式为未选中
           */
          e.target.setContent(markerHtml(false, src, markerStateTemp))
          e.target.setOffset(new AMap.Pixel(-25, -25))
          extData['isSelect'] = false
          this.showAnchors = false
        } else {
          /**
           * 代码段设置选中状态下的标记样式。如果上次为未选中状态isSelect: false，则设置当前样式为未选中
           */
          e.target.setContent(markerHtml(true, src, markerStateTemp))
          e.target.setOffset(new AMap.Pixel(-50, -50))
          extData['isSelect'] = true
          this.showAnchors = true
        }
        extData['markerState'] = markerStateTemp
        extData['src'] = src
        extData['name'] = extDataTemp['name']
        extData['remark'] = extDataTemp['remark']
        extData['zoom'] = extDataTemp['zoom']
        extData['position'] = [e.target.getPosition().lng, e.target.getPosition().lat]
        extData['markerType'] =  extDataTemp['markerType'] || markerType
        e.target.setExtData(extData)
        this.selectMarker = e.target
        this.achorsInfo = extData
      })
      this.map.add([marker])
      this.markers.push({
        marker,
        msg: {
          icon,
          position,
          markerType
        }
      })
      this.saveMarkers(this.markers)
    },
    clickEvent (type) {
      switch (type) {
        case 'save':
          this.saveMarkerMsg()
          break
        case 'delete':
          this.deleteMarkerMsg()
          break
        case 'link':
          this.linkMarkerMsg()
          break
        case 'preview':
          this.previewMarkerMsg()
          break
      }
    },
    previewMarkerMsg () {
      console.log('previewMarkerMsg')
    },
    linkMarkerMsg () {
      this.$alert('锚点关联成功', '操作提示', {
        confirmButtonText: '确定',
        callback: action => {
          var content = `<div class="markerSelect"><img src="${this.achorsInfo.src}" alt=""></div>`
          this.achorsInfo['markerState'] = 'normal'
          this.selectMarker.setContent(content)
          this.selectMarker.setExtData(this.achorsInfo)
        }
      })
    },
    deleteMarkerMsg () {
      this.$confirm('此操作将删除当前选择标注, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.map.remove(this.selectMarker)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    saveMarkerMsg () {
      this.$alert('锚点已编辑', '操作提示', {
        confirmButtonText: '确定',
        callback: action => {
          var content = `<div class="markerSelect"><span class="iconMarkerUnlink"></span><img src="${this.achorsInfo.src}" alt=""></div>`
          this.achorsInfo['markerState'] = 'unLink'
          this.selectMarker.setContent(content)
          this.selectMarker.setExtData(this.achorsInfo)
        }
      })
    },
    markerHandle (e) {
      var icon, markerType
      var position = [e.lnglat.lng, e.lnglat.lat]
      switch (this.pointerCheckedList[0]) {
        case 'icon_car':
          icon = 'icon_car'
          markerType = '警车'
          break
        case 'icon_video':
          icon = 'icon_video'
          markerType = '摄像头'
          break
        default:
          icon = 'icon_point'
          markerType = '治安点'
          break
      }
      this.setMarker({position, icon, markerState: 'unEdit', markerType: markerType})
    },
    markerListener ({type}) {
      if (type === 'add') {
        if (!this.listenerFlag) {
          this.map.on('click', this.markerHandle)
          this.listenerFlag = true
        }
      } else {
        console.log('remove')
        this.map.off('click', this.markerHandle)
        this.listenerFlag = false
      }
    },
    markersInit () {
      var markersMsg = JSON.parse(window.localStorage.getItem('markersMsg')) || []
      markersMsg.forEach(v => {
        this.setMarker({icon: v.icon, position: v.position, markerState: 'unEdit', markerType: v.markerType})
      })
    },
    markerShowManage (markerType) {
      this.markers.forEach(v => {
        if (markerType === 'all') {
          v.marker.show()
          return
        }
        if (v.msg.icon === markerType) {
          v.marker.show()
        } else {
          v.marker.hide()
        }
      })
    },
    changeAnchorsMarkerPosition (position) {
      this.selectMarker.setPosition(position)
    },
    openAndClose () {
      this.openAndCloseFlag ? this.closeSelectZoom() : this.openSelectZoom()
      this.openAndCloseFlag = !this.openAndCloseFlag
    },
    openSelectZoom () {
      this.map.plugin(["AMap.MouseTool"], () => {
        var isDrawRec = false
        this.mouseTool = new AMap.MouseTool(this.map)
        this.mouseTool.rectangle()
        this.selectZoomMouseDownHandler = (e) => {
          this.ancSelectMarkers = []
          if (isDrawRec) {
            var Polygons = this.map.getAllOverlays('Polygon')
            for (var i = 0, l = Polygons.length; i < l - 1; i++) {
              this.map.remove(Polygons[i])
            }
            isDrawRec = false
          }
        }
        this.selectZoomDrawHandler = (e) => {
          var allMarker = this.map.getAllOverlays('Marker')
          isDrawRec = true
          allMarker.forEach(v => {
            if (e.obj.contains(v.getPosition())) {
              this.ancSelectMarkers.push(v)
            }
          })
        }
        this.map.on('mousedown', this.selectZoomMouseDownHandler)
        this.mouseTool.on('draw', this.selectZoomDrawHandler)
      })
    },
    closeSelectZoom () {
      if (!this.mouseTool) {
        return
      }
      var Polygons = this.map.getAllOverlays('Polygon')
      this.ancSelectMarkers = []
      for (var i = 0, l = Polygons.length; i < l; i++) {
        this.map.remove(Polygons[i])
      }
      this.map.off('mousedown', this.selectZoomMouseDownHandler)
      this.mouseTool.off('draw', this.selectZoomDrawHandler)
      this.mouseTool.close()
    }
  },
  watch: {
    pointerCheckedList (cur) {
      var l = cur instanceof Array && cur.length
      l > 0 && cur.indexOf('all') < 0 ? this.markerListener({type: 'add'}) : this.markerListener({type: 'remove'})
      if (l < 2) {
        return this.markerShowManage(cur[l - 1])
      }
      this.pointerCheckedList = [cur[l - 1]]
    },
    achorsInfo: {
      handler: function (cur, old) {
        cur && this.changeAnchorsMarkerPosition(cur.position)
      },
      deep: true
    }
  },
  mounted () {
    this.markersInit()
    this.KeywordLocationMapCenterPoint(this.map, 'pickerInput')
    this.getZoomAndCenter()
    this.$request.anchorTypeQuery({page: 1, pageSize: 10}).then(res => {
      console.log(res)
    })
  },
  components: {
    gMap,
    markerSetPanel,
    locationPanel,
    anchorsBar,
    cameraList,
    markerList
  }
}
</script>
<style rel="stylesheet/less" lang="less">
  .markerSetPanel {
    position: absolute;
    bottom: 20px;
    left: 240px;
  }
  .cancelAllMarkers {
    position: absolute;
    z-index: 6;
    height: 100px;
    width: 100px;
    background-color: #fff;
    color: #222;
  }
  .markerSelect {
    position: relative;
    background: url('../../assets/images/mapIconTest/2dSelect.png') no-repeat center;
    height: 100px;
    width: 100px;
    border-radius: 50%;
    background-size: 100px 100px;
    >.iconMarkerUnedit {
      display: block;
      height: 20px;
      width: 20px;
      background: url('../../assets/images/mapIconTest/2dUnedit.png') no-repeat center;
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 2;
    }
    >.iconMarkerUnlink {
      display: block;
      height: 20px;
      width: 20px;
      background: url('../../assets/images/mapIconTest/2dUnlink.png') no-repeat center;
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 2;
    }
    >img {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate3D(-50%, -50%, 0);
      -ms-transform: translate3D(-50%, -50%, 0);
      -moz-transform: translate3D(-50%, -50%, 0);
      -webkit-transform: translate3D(-50%, -50%, 0);
      -o-transform: translate3D(-50%, -50%, 0);
      z-index: 1;
    }
  }
  .markerUnSelect {
    position: relative;
    height: 50px;
    width: 50px;
    >.iconMarkerUnedit {
      display: block;
      height: 20px;
      width: 20px;
      background: url('../../assets/images/mapIconTest/2dUnedit.png') no-repeat center;
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 2;
    }
    >.iconMarkerUnlink {
      display: block;
      height: 20px;
      width: 20px;
      background: url('../../assets/images/mapIconTest/2dUnlink.png') no-repeat center;
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 2;
    }
    >img {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate3D(-50%, -50%, 0);
      -ms-transform: translate3D(-50%, -50%, 0);
      -moz-transform: translate3D(-50%, -50%, 0);
      -webkit-transform: translate3D(-50%, -50%, 0);
      -o-transform: translate3D(-50%, -50%, 0);
      z-index: 1;
    }
  }
  /* 摄像头面板 */
  .cameraList {
    position: absolute;
    width: 60%;
    max-width: 700px;
    height: 60%;
    top: 20%;
    left: 50%;
    margin-left: -30%;
    z-index: 9999;
  }
  .ancSelectBox {
    position: absolute;
    bottom: 100px;
    left: 240px;
    background: url('../../assets/images/mapIconTest/2dBoxChecked.png');
    background-size: 60px 60px;
    height: 60px;
    width: 60px;
    cursor: pointer;
    img {
      width: 40px;
      margin-top: 8px;
      margin-left: 12px;
    }
  }
  .ancUnSelectBox {
    position: absolute;
    bottom: 100px;
    left: 240px;
    background: url('../../assets/images/mapIconTest/2dBox.png');
    background-size: 60px 60px;
    height: 60px;
    width: 60px;
    cursor: pointer;
    img {
      width: 40px;
      margin-top: 8px;
      margin-left: 12px;
    }
  }
  .markerList {
    position: absolute;
    top: 500px;
    left: 500px;
    z-index: 3;
  }
</style>
